package com.example.graduatedesigned.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.graduatedesigned.R;
import com.example.graduatedesigned.bean.DataResponse;
import com.example.graduatedesigned.bean.DeviceHistoryItem;
import com.example.graduatedesigned.bean.HistoryBean;
import com.example.graduatedesigned.http.ApiService;
import com.example.graduatedesigned.http.RetrofitClient;
import com.example.graduatedesigned.utils.DevicesInfo;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChartFragment extends Fragment {
    private String mParam1;
    private static final String ARG_PARAM1 = "param1";
    private PieChart mPieChart;
    public static ChartFragment newInstance(String param1) {
        ChartFragment fragment = new ChartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            ApiService service = RetrofitClient.getInstance();
            String productId = DevicesInfo.product_id;
            String deviceName = DevicesInfo.device_name;
            String auto = DevicesInfo.auth_info;
            long endTime = System.currentTimeMillis();
            long startTime = endTime - 7 * 24 * 60 * 60 * 1000;
            Call<DataResponse<HistoryBean>> call = service.getDeviceHistory(productId, deviceName, auto, startTime, endTime, mParam1);
            call.enqueue(new Callback<DataResponse<HistoryBean>>() {
                @Override
                public void onResponse(Call<DataResponse<HistoryBean>> call, Response<DataResponse<HistoryBean>> response) {
                    if (response.body() == null) {
                        return;
                    }
                    List<DeviceHistoryItem> hisList = response.body().getData().getList();
                    updateUI(hisList);
                }

                @Override
                public void onFailure(Call<DataResponse<HistoryBean>> call, Throwable t) {
                }
            });
        }
    }

    private void updateUI(List<DeviceHistoryItem> hisList) {
        mPieChart.setUsePercentValues(true); // 设置为显示百分比
        Description description = new Description();
        String desc = mParam1.equals("humi") ? "湿度" : "温度";
        description.setText("最近10条"+desc+"数据展示");
        description.setTextSize(20f);
        description.setPosition(1000,300);
        mPieChart.setDescription(description); // 设置描述
        mPieChart.setDrawCenterText(true); // 设置可以绘制中间的文字
        mPieChart.setCenterTextColor(Color.BLACK); // 中间的文本颜色
        mPieChart.setCenterTextSize(18f); // 设置中间文本文字的大小
        mPieChart.setDrawHoleEnabled(true); // 绘制中间的圆形
        mPieChart.setHoleColor(Color.WHITE); // 饼状图中间的圆的绘制颜色
        mPieChart.setHoleRadius(40f); // 饼状图中间的圆的半径大小
        mPieChart.setTransparentCircleColor(Color.BLACK); // 设置圆环的颜色
        mPieChart.setTransparentCircleAlpha(100); // 设置圆环的透明度[0,255]
        mPieChart.setTransparentCircleRadius(40f); // 设置圆环的半径值
        mPieChart.setRotationEnabled(false); // 设置饼状图是否可以旋转(默认为true)
        mPieChart.setRotationAngle(10f); // 设置饼状图旋转的角度
        Legend l = mPieChart.getLegend(); // 设置比例图
        l.setMaxSizePercent(100f);
        l.setTextSize(12f);
        l.setXEntrySpace(10f);
        l.setYEntrySpace(5f); // 设置tab之间Y轴方向上的空白间距值
        l.setYOffset(0f);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER); // 垂直居中
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); // 水平右对齐
        l.setOrientation(Legend.LegendOrientation.VERTICAL); // 强制设置为垂直排列

        // 饼状图上字体的设置
        mPieChart.setDrawEntryLabels(false); // 设置是否绘制Label
        mPieChart.setEntryLabelTextSize(23f); // 设置绘制Label的字体大小

        // 设置数据百分比和描述
        ArrayList<PieEntry> pieEntries = getFixedList(hisList, desc);
        mPieChart.setHoleRadius(0f); // 设置中间的空白区域的半径为0，即实心圆
        mPieChart.setTransparentCircleRadius(0f); // 设置透明圆的半径为0，即实心圆
        PieDataSet pieDataSet = new PieDataSet(pieEntries, "");
        ArrayList<Integer> colors = new ArrayList<>();
        Random random = new Random();

        // 饼图颜色
        for (int i =0;i<pieEntries.size();++i) {
            int r = random.nextInt(256);
            int g = random.nextInt(256);
            int b = random.nextInt(256);
            int color = Color.rgb(r, g, b);
            colors.add(color);
        }
        pieDataSet.setColors(colors);
        pieDataSet.setSliceSpace(0f); // 设置选中的Tab离两边的距离
        pieDataSet.setSelectionShift(5f); // 设置选中的tab的多出来的
        PieData pieData = new PieData(pieDataSet);

        // 自定义格式
        pieData.setValueFormatter(new ValueFormatter() {
            // 格式化数据，并加上百分号
            @Override
            public String getFormattedValue(float value) {
                return value == 0f || Float.isNaN(value) ? "" : String.format("%.2f", value) + "%";
            }
        });
        pieData.setValueTextSize(15f);
        pieData.setValueTextColor(Color.BLUE);
        mPieChart.setData(pieData);
        mPieChart.highlightValues(null);
        mPieChart.invalidate();
    }

    private ArrayList<PieEntry> getFixedList(List<DeviceHistoryItem> hisList, String desc) {
        Map<String, Integer>map = new HashMap<>();
        ArrayList<PieEntry>list = new ArrayList<>();
        for (DeviceHistoryItem item: hisList) {
            map.put(item.getValue(), map.getOrDefault(item.getValue(), 0) + 1);
        }
        for (String key: map.keySet()) {
            if (desc.equals("湿度")) {
                list.add(new PieEntry(map.get(key), key + "%"));
            } else {
                list.add(new PieEntry(map.get(key), key + "℃"));
            }
        }
        return list;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_chart, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPieChart = view.findViewById(R.id.mPieChart);
    }

}
